const express=require('express');
const router=express.Router();
const db=require('../db')
const md5=require('md5')
const jwt=require('jsonwebtoken')

//注册功能
router.post('/reguser',(req,res)=>{
  let {username,password}=req.body
  console.log(req.body);
  db(`select * from user where username='${username}'` ,(err,result)=>{
    if(err) throw err
    if(result.length>0){
      res.send({status:1,message:'用户名已经存在!'})
    }else{
      password=md5(password);
      db(`insert into user set username='${username}', password='${password}'`,(e,r)=>{
        if(e) throw e
        res.send({status:0,message:'添加成功!'})
      })
    }
  })
 
})
//登录
router.post('/login',(req,res)=>{
  let {username,password}=req.body;
  password=md5(password)
  db(`select * from user  where username="${username}" and password="${password}"`,(err,result)=>{
    if(err) throw err
    console.log(result);
    if(result.length>0){
      //设置token
      let token=jwt.sign({id:result[0].id},'tanghe',{expiresIn:'2h'});
      res.send({status:0,message:'登陆成功!',token:"Beorer" + token})
    }else{
      res.send({status:1,message:"账号或密码错误"})
    }
  })
})


module.exports=router;